import Vue from 'vue';
import VueResource from 'vue-resource'
import iView from 'iview';
import {router} from './router/index';
import {routers, otherRouter, appRouter} from './router/router';
import store from './store';
import App from './app.vue';
import 'iview/dist/styles/iview.css';
import Util from './libs/util';
import Cookies from 'js-cookie';

Vue.use(iView);
Vue.use(VueResource);

Vue.http.options.emulateJSON = true;

function ajax(method, url, data, callback) {
  data = data || {};
  data.token = localStorage.token || ""; // 设置token
  for(var key in data) {
      if(data[key] != null && data[key] instanceof Object) data[key] = JSON.stringify(data[key]);
  }
  Vue.http[method](url, data).then(function(res) {
    if(res.body.status == 10000) {
      callback(res.body);
    }else if(res.body.status == 10611) { // 未登录或session失效
      alert(res.body.message);
      vm.$store.commit("logout", vm);
      vm.$router.push("/login");
    }else {
      var error_str = `请求错误，错误码：${res.body.status},错误信息：${res.body.message}`;
      console.log(error_str);
      Vue.prototype.$Message.error(error_str);
    }
  });
}
Vue.prototype.api = {
  api_url: "/api/",
  get: function(url, data, callback) {
    ajax("get", this.api_url+url, data, callback);
  },
  post: function(url, data, callback) {
    ajax("post", this.api_url+url, data, callback);
  }
}
Vue.prototype.global = {
  me: { }
}


var vm = new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    mounted () {
        this.$store.commit('updateMenulist');
    }
});


router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  Util.title(to.meta.title);
  if (!Cookies.get('access') && to.name !== 'login') { // 判断是否未登录且前往的页面不是登录页
      next({
          name: 'login'
      });
  } else if (Cookies.get('access') && to.name === 'login') { // 判断是否已经登录且前往的是登录页
      Util.title();
      next({
          name: 'home_index'
      });
  } else {
      const curRouterObj = Util.getRouterObjByName([otherRouter, ...appRouter], to.name);
      if (curRouterObj && curRouterObj.permission !== undefined) { // 需要判断权限的路由
          if (Cookies.get('access') && Util.showThisRoute(curRouterObj.permission, vm.$store.state.user.info.permission)) {
              Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next); // 如果在地址栏输入的是一级菜单则默认打开其第一个二级菜单的页面
          } else {
              next({
                  replace: true,
                  name: 'error-403'
              });
          }
      } else { // 没有配置权限的路由, 直接通过
          Util.toDefaultPage([...routers], to.name, router, next);
      }
  }
});

router.afterEach((to) => {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
});